/**
 *  函数防抖
 *  @param {Function} func  包装的函数
 *  @param {num} delay      延迟时间
 *  @param {boolean} immediate 第一次滚动会执行两次  开始滚动和结束滚动的时候
 *  @return {*}
 */

export function debounce(func, delay, immediate = false) {
  let timer
  const context = this
  return (...args) => {
    if (immediate) {
      func.apply(context, args)
      // eslint-disable-next-line no-param-reassign
      immediate = false
      return
    }
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(context, args)
    }, delay)
  }
}
/**
 *  通过高德获取geoJson
 *  @param {string} abcode     行政区code
 *  @param {string} geoJson    上一次获取的geoJson数据
 *  @return {}
 */

export function getGeoJson(adcode, geoJson = []) {
  return new Promise((resolve, reject) => {
    window.AMapUI.loadUI(["geo/DistrictExplorer"], (DistrictExplorer) => {
      const districtExplorer = new DistrictExplorer()
      districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
        if (error) {
          reject(error)
          return
        }
        let Json = areaNode.getSubFeatures()
        const mapJson = {
          features: []
        }
        if (Json.length === 0) {
          if (geoJson.features) {
            Json = geoJson.features.filter(
              (item) => item.properties.adcode === adcode
            )
          }
        }
        mapJson.features = Json
        resolve(mapJson)
      })
    })
  })
}

const utils = {
  debounce,
  getGeoJson
}

/**
 * 外链打开新页面
 * @param { string } url 链接地址
 */
utils.open = (url) => {
  const a = document.createElement("a")
  a.setAttribute("href", url)
  a.setAttribute("target", "_blank")
  a.setAttribute("id", "admin-link-temp")
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById("admin-link-temp"))
}

export default utils
